<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { Modal, message } from 'ant-design-vue'
import { ClockCircleOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import type { Dayjs } from 'dayjs'
import { getWebsiteContentsApi, updateWebsiteContentApi, type WebsiteContentItem } from '~/api/common/login'

defineOptions({
  name: 'ContentReviewList',
})

const loading = ref(false)
const allReviewList = ref<WebsiteContentItem[]>([])
const selectedIds = ref<number[]>([])
const drawerVisible = ref(false)
const currentArticle = ref<WebsiteContentItem | null>(null)

const searchForm = reactive({
  keyword: '',
  publishRange: undefined as [Dayjs, Dayjs] | [string, string] | undefined,
})

const reviewList = computed(() => {
  let list = allReviewList.value.filter(item => item.publish_status === 1)
  
  // 关键词筛选
  const keyword = searchForm.keyword.trim().toLowerCase()
  if (keyword) {
    list = list.filter((item) => {
      const title = (item.title || '').toLowerCase()
      const author = (item.author || '').toLowerCase()
      const handler = (item.created_by || '').toLowerCase()
      const channel = (item as any).channel_name ? String((item as any).channel_name).toLowerCase() : ''
      return title.includes(keyword) || author.includes(keyword) || handler.includes(keyword) || channel.includes(keyword)
    })
  }
  
  // 日期范围筛选
  if (searchForm.publishRange && searchForm.publishRange.length === 2) {
    const [start, end] = searchForm.publishRange
    const startTime = new Date(typeof start === 'string' ? start : (start as any).format('YYYY-MM-DD')).getTime()
    const endTime = new Date(`${typeof end === 'string' ? end : (end as any).format('YYYY-MM-DD')} 23:59:59`).getTime()
    list = list.filter((item) => {
      if (!item.publish_time)
        return false
      const publishTime = new Date(item.publish_time).getTime()
      return publishTime >= startTime && publishTime <= endTime
    })
  }
  
  // 按时间倒序排序，最新的放前面
  return list.sort((a, b) => {
    const timeA = new Date(a.updated_at || a.created_at || 0).getTime()
    const timeB = new Date(b.updated_at || b.created_at || 0).getTime()
    return timeB - timeA
  })
})

function handleSearch() {
  // 搜索逻辑已在computed中处理
}

function handleReset() {
  searchForm.keyword = ''
  searchForm.publishRange = undefined
}

async function fetchList() {
  loading.value = true
  try {
    const res = await getWebsiteContentsApi({ channel_id: undefined })
    if (res.code === 0 && Array.isArray(res.data))
      allReviewList.value = res.data.filter(item => item.publish_status === 1)
    else
      allReviewList.value = []
  } catch (error) {
    console.error(error)
    allReviewList.value = []
  } finally {
    loading.value = false
  }
}

function formatTime(value?: string) {
  if (!value)
    return '-'
  return new Date(value).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function handleView(item: WebsiteContentItem) {
  currentArticle.value = item
  drawerVisible.value = true
}

function handleDrawerClose() {
  drawerVisible.value = false
  currentArticle.value = null
}

function formatDate(dateString: string): string {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

async function handleApprove(item: WebsiteContentItem) {
  Modal.confirm({
    title: '审核通过确认',
    content: `确定通过《${item.title}》的审核吗？`,
    okText: '通过',
    cancelText: '取消',
    okButtonProps: { style: { backgroundColor: '#428bca', border: 'none', borderRadius: '0', color: '#fff' } } as any,
    cancelButtonProps: { style: { borderRadius: '0' } } as any,
    centered: true,
    onOk: async () => {
      try {
        await updateWebsiteContentApi({ id: item.id, publish_status: 2 })
        message.success('审核已通过')
        fetchList()
        selectedIds.value = selectedIds.value.filter(id => id !== item.id)
      } catch (error: any) {
        message.error(error?.message || '操作失败，请稍后重试')
      }
    },
  })
}

async function handleReject(item: WebsiteContentItem) {
  Modal.confirm({
    title: '打回确认',
    content: `确定打回《${item.title}》吗？文章将返回草稿状态。`,
    okText: '打回',
    cancelText: '取消',
    okButtonProps: { style: { backgroundColor: '#c03421', border: 'none', borderRadius: '0', color: '#fff' } } as any,
    cancelButtonProps: { style: { borderRadius: '0' } } as any,
    centered: true,
    onOk: async () => {
      try {
        await updateWebsiteContentApi({ id: item.id, publish_status: 0 })
        message.success('已打回草稿')
        fetchList()
        selectedIds.value = selectedIds.value.filter(id => id !== item.id)
      } catch (error: any) {
        message.error(error?.message || '操作失败，请稍后重试')
      }
    },
  })
}

function handleRowSelectChange(id: number, checked: boolean) {
  if (checked) {
    if (!selectedIds.value.includes(id)) {
      selectedIds.value.push(id)
    }
  } else {
    selectedIds.value = selectedIds.value.filter(selectedId => selectedId !== id)
  }
}

async function handleBatchApprove() {
  if (selectedIds.value.length === 0) {
    Modal.warning({
      title: '提示',
      content: '请先选择需要审核通过的文章',
      okText: '好的',
      okButtonProps: { style: { backgroundColor: '#428bca', border: 'none', borderRadius: '0', color: '#fff' } } as any,
      centered: true,
    })
    return
  }

  const selectedItems = reviewList.value.filter(item => selectedIds.value.includes(item.id))

  Modal.confirm({
    title: '批量审核通过确认',
    content: `确定要通过 ${selectedItems.length} 篇文章的审核吗？`,
    okText: '确定',
    cancelText: '取消',
    okButtonProps: { style: { backgroundColor: '#428bca', border: 'none', borderRadius: '0', color: '#fff' } } as any,
    cancelButtonProps: { style: { borderRadius: '0' } } as any,
    centered: true,
    onOk: async () => {
      try {
        await Promise.all(
          selectedItems.map(item =>
            updateWebsiteContentApi({
              id: item.id,
              publish_status: 2,
            }),
          ),
        )

        Modal.success({
          title: '提示',
          content: `成功通过 ${selectedItems.length} 篇文章的审核`,
          okText: '好的',
          okButtonProps: { style: { backgroundColor: '#428bca', border: 'none', borderRadius: '0', color: '#fff' } } as any,
          centered: true,
          onOk: () => {
            fetchList()
            selectedIds.value = []
          },
        })
      } catch (error: any) {
        const errorMsg = error?.message || error?.msg || '批量审核失败，请稍后重试'
        message.error(errorMsg)
      }
    },
  })
}

function handleRefresh() {
  selectedIds.value = []
  fetchList()
}

onMounted(() => {
  fetchList()
})
</script>

<template>
  <page-container>
    <div class="review-page">
      <div class="review-header">
        <div>
          <h2>内容审核</h2>
          <p>审核待发布的稿件，控制上线质量</p>
        </div>
        <a-space>
          <a-button
            class="batch-approve-btn"
            type="primary"
            :disabled="selectedIds.length === 0"
            @click="handleBatchApprove">
            批量通过 ({{ selectedIds.length }})
          </a-button>
          <a-button
            class="refresh-btn"
            @click="handleRefresh">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
        </a-space>
      </div>

      <!-- 筛选工具栏 -->
      <div class="review-toolbar">
        <a-form :model="searchForm" layout="inline" class="toolbar-form">
          <a-form-item>
            <template #label>
              <span class="toolbar-label">关键词</span>
            </template>
            <a-input
              v-model:value="searchForm.keyword"
              placeholder="请输入标题、作者、编辑人等关键词"
              class="toolbar-input"
              allow-clear
              @press-enter="handleSearch"
            />
          </a-form-item>
          
          <a-form-item>
            <template #label>
              <span class="toolbar-label">提交时间</span>
            </template>
            <a-range-picker
              v-model:value="searchForm.publishRange"
              class="toolbar-range-picker"
              format="YYYY-MM-DD"
            />
          </a-form-item>
          
          <a-form-item>
            <a-space>
              <a-button
                class="review-primary-btn"
                type="primary"
                @click="handleSearch">
                查询
              </a-button>
              <a-button 
                class="review-ghost-btn"
                @click="handleReset">
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <a-spin size="large" />
      </div>

      <!-- 空状态 -->
      <div v-else-if="reviewList.length === 0" class="empty-container">
        <a-empty description="暂无待审核内容" :image="false" />
      </div>

      <!-- 卡片列表 -->
      <div v-else class="card-table-container">
        <div class="card-table">
          <div
            v-for="item in reviewList"
            :key="item.id"
            class="table-card"
            :class="{ 'selected': selectedIds.includes(item.id) }"
          >
            <div class="card-checkbox">
              <a-checkbox
                :checked="selectedIds.includes(item.id)"
                @change="(e: any) => handleRowSelectChange(item.id, e.target.checked)"
              />
            </div>

            <div class="card-content">
              <!-- 第一行：仅展示标题 -->
              <div class="card-row first-row">
                <div class="title-section">
                  <button class="title-link" type="button" @click="handleView(item)">
                    {{ item.title }}
                  </button>
                  <span v-if="item.is_top === 1" class="top-flag">顶</span>
                </div>
              </div>

              <!-- 第二行：详细信息 -->
              <div class="card-row second-row">
                <div class="info-section">
                  <div class="info-item">
                    <span class="info-label">作者：</span>
                    <span class="info-value">{{ item.author || '-' }}</span>
                  </div>

                  <div class="info-item">
                    <span class="info-label">浏览量：</span>
                    <span class="info-value">{{ item.view_count ?? 0 }}</span>
                  </div>

                  <div class="info-item">
                    <span class="info-label">编辑人：</span>
                    <span class="info-value">{{ item.created_by || '-' }}</span>
                  </div>

                  <div class="info-item">
                    <span class="info-label">编辑时间：</span>
                    <span class="info-value">{{ formatTime(item.updated_at) }}</span>
                  </div>

                  <div class="info-item">
                    <span class="info-label">提交时间：</span>
                    <span class="info-value">{{ formatTime(item.updated_at || item.created_at) }}</span>
                  </div>

                  <div class="info-item">
                    <span class="info-label">栏目：</span>
                    <span class="info-value">{{ item.channel_name || '-' }}</span>
                  </div>

                  <div class="info-item">
                    <span class="info-label">状态：</span>
                    <span class="status-pill pending">
                      <ClockCircleOutlined style="color: #fa8c16; font-size: 18px; font-weight: bold;" />
                      <span>等待审核中</span>
                    </span>
                  </div>
                </div>

                <div class="actions-section">
                  <a-space size="small" wrap>
                    <button
                      class="text_button"
                      @click="handleView(item)"
                    >
                      查看
                    </button>
                    <button
                      class="text_button approve-action"
                      @click="handleApprove(item)"
                    >
                      通过
                    </button>
                    <button
                      class="text_button reject-action"
                      @click="handleReject(item)"
                    >
                      打回
                    </button>
                  </a-space>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 文章详情抽屉 -->
      <a-drawer
        v-model:open="drawerVisible"
        :title="currentArticle?.title || '文章详情'"
        placement="right"
        width="800"
        destroy-on-close
        class="article-drawer"
        @close="handleDrawerClose"
      >
        <template v-if="currentArticle">
          <div class="drawer-content">
            <!-- 简化的元信息 -->
            <div class="article-meta-info-compact">
              <span class="meta-item-compact">栏目：{{ currentArticle.channel_name || currentArticle.channel_id || '-' }}</span>
              <span class="meta-item-compact">作者：{{ currentArticle.author || '-' }}</span>
              <span class="meta-item-compact">{{ formatDate(currentArticle.publish_time) }}</span>
            </div>

            <!-- 封面图片（小一点） -->
            <div v-if="currentArticle.cover_image || (currentArticle as any).cover_url" class="article-cover-compact">
              <img :src="currentArticle.cover_image || (currentArticle as any).cover_url" alt="文章封面">
            </div>

            <!-- 正文内容（主要展示） -->
            <div class="article-content-section">
              <div class="content-text" v-html="currentArticle.content || '-'"></div>
            </div>
          </div>
        </template>
        <div v-else class="drawer-empty">
          <a-empty description="暂无数据" />
        </div>
      </a-drawer>
    </div>
  </page-container>
</template>

<style scoped lang="less">
@import '../dashboard/analysis/index.css';

.review-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  background-color: transparent;
  min-height: calc(100vh - 120px);
  font-size: 16px;
}

.review-header {
  padding: 18px 22px;
  border-radius: 0;
  background: transparent;
  border: none;
  display: flex;
  justify-content: space-between;
  align-items: center;

  h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #1f2329;
  }

  p {
    margin: 6px 0 0;
    color: #8a909f;
    font-size: 14px;
  }
}

.review-toolbar {
  padding: 16px;
  background: transparent;
  margin-bottom: 16px;
}

.toolbar-form {
  display: flex;
  flex-wrap: wrap;
  gap: 14px;

  :deep(.ant-form-item) {
    margin-bottom: 0;
  }
}

.toolbar-label {
  color: #1f2329;
  font-size: 14px;
  font-weight: 500;
  margin-right: 8px;
}

.toolbar-input {
  width: 260px;
  border-radius: 0;

  :deep(.ant-input) {
    border-radius: 0;
  }
}

.toolbar-range-picker {
  border-radius: 0;
  min-width: 240px;

  :deep(.ant-picker-range) {
    border-radius: 0;
  }
}

.review-primary-btn {
  background: linear-gradient(135deg, #428bca, #5c9cd6);
  border: none;
  border-radius: 0;
  color: #fff;
  min-width: 88px;
  height: 36px;
  font-weight: 500;
}

.review-ghost-btn {
  border-radius: 0;
  border-color: #428bca;
  color: #428bca;

  &:hover {
    color: #fff;
    background: #428bca;
    border-color: #428bca;
  }
}

.batch-approve-btn {
  background: linear-gradient(135deg, #428bca 0%, #5c9cd6 100%);
  border: none;
  border-radius: 0;
  height: 40px;
  font-weight: 500;

  &:disabled {
    opacity: 0.55;
  }
}

.refresh-btn {
  border-radius: 0;
  height: 40px;
  border-color: #428bca;
  color: #428bca;

  &:hover {
    color: #fff;
    background: #428bca;
    border-color: #428bca;
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background-color: transparent;

  :deep(.ant-empty) {
    .ant-empty-image {
      display: none;
    }

    .ant-empty-description {
      color: #999;
      font-size: 16px;
    }
  }
}

.text_button {
  border: none;
  color: #428BCA;
  font-size: 16px;
  font-weight: 500;
  background-color: transparent;
  cursor: pointer;
  padding: 0;
  transition: color 0.2s;

  &:hover {
    color: #5c9cd6;
    background-color: transparent;
  }

  &.approve-action {
    color: #428BCA;

    &:hover {
      color: #5c9cd6;
    }
  }

  &.reject-action {
    color: #428BCA;

    &:hover {
      color: #5c9cd6;
    }
  }
}

.status-pill {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 600;

  &.pending {
    background: #fff7e6;
    color: #fa8c16;
    border: 1px solid #ffd591;
  }
}

.top-flag {
  width: 22px;
  height: 22px;
  border-radius: 4px;
  background: #ff4d4f;
  color: white;
  font-size: 12px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.article-drawer {
  :deep(.ant-drawer-header) {
    border-bottom: 1px solid #e4e7ed;
  }

  :deep(.ant-drawer-body) {
    padding: 24px;
  }
}

.drawer-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.article-meta-info-compact {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 8px 0;
  font-size: 12px;
  color: #999;
  border-bottom: 1px solid #f0f0f0;
}

.meta-item-compact {
  color: #999;
  font-size: 12px;
}

.article-cover-compact {
  width: 100%;
  max-height: 200px;
  overflow: hidden;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;

  img {
    max-width: 100%;
    max-height: 200px;
    object-fit: contain;
  }
}

.article-content-section {
  .content-text {
    font-size: 14px;
    line-height: 1.8;
    color: #333;
    word-wrap: break-word;
    
    :deep(img) {
      max-width: 100%;
      height: auto;
    }
    
    :deep(p) {
      margin-bottom: 12px;
    }
  }
}

.drawer-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
}
</style>
